package com.idemon.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;

import java.util.Date;

/**
 * 自定义的任务Trigger
 * 可以实现直接指定任意的任务触发日期（例如：考勤只能指定工作日）
 *
 * @author idemon
 * @since 2020-10-27 10:40
 */
@Slf4j
public class AssignDateTrigger implements Trigger {

    private TaskDateService taskDateService;

    private Long taskConfigId;

    public AssignDateTrigger(TaskDateService taskDateService, Long taskConfigId) {
        this.taskDateService = taskDateService;
        this.taskConfigId = taskConfigId;
    }

    @Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        Date lastExecution = triggerContext.lastScheduledExecutionTime();
        // 任务初次启动时为空，默认为当前时间
        if(lastExecution == null){
            lastExecution = new Date();
        }
        // 取出当前时间之后的最近的一次触发日期并返回，即下一次任务触发时间
        Date newDate = taskDateService.getNextDate(taskConfigId,lastExecution);
        if(newDate == null || newDate.before(new Date())){
            log.info("===>The nextExecutionTime[{}] of Task[taskConfigId:{}] is null or before now",newDate,
                    taskConfigId);
        }
        return newDate;
    }
}
